<template>
  <div class="dataContainer">
    <!-- Search start -->
    <el-form :inline="true" size="small" :model="queryParams" class="demo-form-inline searchContainer">
      <el-form-item label="姓名: ">
        <el-input v-model="queryParams.name" placeholder="请输入姓名"  @keyup.enter="onSearch"  style="width: 180px;"/>
      </el-form-item>
      <el-form-item label="微信号: ">
        <el-input v-model="queryParams.wechatID" placeholder="请输入微信号"  @keyup.enter="onSearch"  style="width: 180px;"/>
      </el-form-item>
      <!-- <el-form-item label="自媒体平台: ">
        <el-select
            v-model="queryParams.weMediaPlatform"
            placeholder="自媒体平台" 
            style="width: 150px;"
            clearable
        >
            <el-option
            v-for="item in weMediaPlatformList"
            :key="item.dicValue"
            :label="item.dicName"
            :value="item.dicValue"
            />
        </el-select>
      </el-form-item> -->
      <el-form-item label="账号:" prop="account">
        <template #label>
            <el-tooltip
                class="box-item"
                effect="dark"
                content="保证金监控中心账号"
                placement="bottom-start"
            >
                <span><el-icon style="font-size: 15px;vertical-align: sub;"><QuestionFilled /></el-icon>账号:</span>
            </el-tooltip>
        </template>
        <el-input v-model="queryParams.account" placeholder="请输入保证金监控中心账号" style="width: 180px;" clearable ></el-input>
      </el-form-item>
      <el-form-item label="引流日期: ">
        <!-- value-format指定时间格式, 否则时长差8小时 -->
        <el-date-picker
            style="width: 170px;"
            v-model="queryParams.recommendedDateStart"
            type="date"
            :disabled-date="disabledDateStart"
            value-format="YYYY-MM-DD"
            placeholder="选择开始日期"
        />
        <span>
          <svg t="1758243204848" class="icon" style="vertical-align: middle;" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5276" 
            width="1.4em" height="1.4em"><path d="M359.354037 457.937888c-3.180124 9.540373-12.720497 15.900621-22.260869 19.080746-9.540373 3.180124-19.080745 3.180124-25.440994 0s-12.720497-9.540373-15.900621-19.080746c-3.180124-9.540373-3.180124-22.26087 3.180124-38.16149 3.180124-12.720497 9.540373-22.26087 19.080745-34.981367 6.360248-9.540373 15.900621-19.080745 25.440994-28.621118s22.26087-15.900621 34.981367-19.080745c12.720497-6.360248 28.621118-6.360248 47.701863-6.360249 25.440994 0 44.521739 6.360248 57.242236 15.900621 12.720497 9.540373 28.621118 22.26087 38.161491 31.801243 12.720497 12.720497 22.26087 22.26087 34.981366 31.801242 12.720497 9.540373 31.801242 15.900621 54.062112 12.720497 15.900621 0 28.621118-3.180124 38.161491-9.540373s19.080745-12.720497 25.440993-19.080745 9.540373-15.900621 12.720497-22.26087 3.180124-15.900621 6.360249-22.260869c0-9.540373 6.360248-19.080745 12.720497-22.26087 6.360248-3.180124 15.900621-6.360248 22.260869-6.360248 9.540373 0 15.900621 3.180124 22.26087 9.540372 6.360248 6.360248 9.540373 12.720497 9.540372 22.26087s-3.180124 22.26087-6.360248 38.161491-12.720497 31.801242-22.26087 47.701863c-12.720497 15.900621-25.440994 28.621118-44.521739 41.341615-19.080745 12.720497-44.521739 15.900621-73.142857 15.900621-28.621118 0-50.881988-3.180124-69.962733-12.720497-19.080745-9.540373-31.801242-19.080745-44.521739-31.801242l-31.801242-31.801242c-9.540373-9.540373-22.26087-15.900621-34.981367-15.900622-9.540373 0-19.080745 0-25.440993 3.180125-6.360248 3.180124-12.720497 9.540373-19.080746 12.720497-6.360248 6.360248-9.540373 12.720497-12.720497 19.080745-9.540373 9.540373-12.720497 15.900621-15.900621 19.080745z" 
            fill="#8a8a8a" p-id="5277"></path></svg>
        </span>
        <el-date-picker
            style="width: 170px;"
            v-model="queryParams.recommendedDateEnd"
            type="date"
            :disabled-date="disabledDateEnd"
            value-format="YYYY-MM-DD"
            placeholder="选择结束日期"
        />
      </el-form-item>
      <!-- <el-form-item label="状态:">
        <el-select v-model="queryParams.status" placeholder="请选择" collapse-tags clearable  style="width: 180px">
          <el-option label="正常" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button class="bs-form-btn" size="small" type="primary" @click="onSearch" ><el-icon><Search /></el-icon>查 询</el-button>
        <ResetButton :queryParams="queryParams"/>
        <el-button size="small" type="primary" @click="openAddModal"><el-icon><Plus /></el-icon>新增 </el-button>
        <el-button size="small" type="primary" @click="exportDate"><el-icon><Download /></el-icon>导出 </el-button>
      </el-form-item>
    </el-form>
    <!-- Search end -->

    <!-- Table start -->
    <div >
      <ColumnSetting v-model:columnList="columnList" />
      <el-table
        ref="tableRef"
        v-loading="tableLoading"
        :border="true"
        class="bs-table"
        :data="tableData"
        row-key="id"
        :height="tableHeight"
        :header-cell-style="{textAlign: 'center'}"
        :cell-style="{textAlign: 'center'}"
      >
        <el-table-column type="index" label="序号" width="80" fixed/>
        <template v-for="item in columnList" :key="item.prop">
          <el-table-column :prop="item.prop" :label="item.label"  :fixed="item.fixed" :sortable:="item.sortable" v-if="!item.hide && item.prop!='action'" :width="item.width">
            <template #default="scope">
              <template v-if="item.prop=='status'">
                <div v-if="scope.row.status==1">
                    <el-tag type="primary">正常</el-tag>
                </div>
                <div v-else>  
                    <el-tag type="info">禁用</el-tag>
                </div>
              </template>
              <template v-else-if="item.prop=='name'">
                {{ scope.row.code }} - {{ scope.row.name }}
              </template>
              <template v-else-if="item.prop=='password'">
                <el-tooltip
                  v-if="isNotBlank(scope.row.password)"
                  class="box-item"
                  effect="dark"
                  :content="scope.row.password"
                  placement="bottom-start"
                  :teleported="true"
                >
                  <span>******</span>
                </el-tooltip>
              </template>
              <template v-else-if="item.prop=='loginPassword'">
                <el-tooltip
                  v-if="isNotBlank(scope.row.loginPassword)"
                  class="box-item"
                  effect="dark"
                  :content="scope.row.loginPassword"
                  placement="bottom-start"
                  :teleported="true"
                >
                  <span>******</span>
                </el-tooltip>
              </template>
              <template v-else>
                {{ scope.row[item.prop] }}
              </template>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" :width="item.width" v-else-if="!item.hide && item.prop=='action'">
             <template #default="scope">
              <el-button  size="small" link type="success"  @click="editRow(scope.row.id)" ><el-icon><Edit /></el-icon> 修改</el-button>
              <el-button  size="small" link type="primary" @click="openMergeModel(scope.row.id)" ><el-icon><Switch /></el-icon> 合并</el-button>
              <el-button  size="small" link type="danger" @click="deleteRow(scope.row.id)" ><el-icon><Delete /></el-icon> 删除</el-button>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <pagination
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        small="small"
        disabled="disabled"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableTotal"
        @pagination="selectByPage"
      />
    </div>
    <AddStudent ref="addOrUpdateRef" @flushTable="selectByPage"  />
    <el-dialog
      title="合并学员信息"
      v-model="mergeVisable"
      width="45%"
      :close-on-click-modal="false"
      :draggable="true"
    >
      <p>
        <span style="color: red;">注意 : </span>
        从
        <span style="color: var(--el-color-success-dark-2);">左侧</span>
        合并到
        <span style="color: blue;">右侧</span>
      </p>
      <el-form
          ref="mergeFormRef"
          :model="mergeFormData"
          :rules="mergeFormRules"
          label-width="auto"
          style="width: 90%;margin-left: 5%;"
        >
          <el-row :gutter="25">
            <el-col :span="12">
              <el-form-item label="学员:" prop="fromStudentID">
                <el-select
                  filterable
                  v-model="mergeFormData.fromStudentID"
                  placeholder="请选择学员" 
                  clearable
                >
                <el-option
                    v-for="item in studentList"
                    :key="item.id"
                    :label="item.code+'-'+item.wechatNickname+'-'+item.phone"
                    :value="item.id"
                  >
                      <div>
                      <div style="display: inline-block;width: 200px;">
                        <span title="学员编号">{{ item.code }}</span>
                        <span title="微信昵称" style="float:right;color:#c7c7c7;margin-right: 5px;">{{ item.wechatNickname }}</span>
                      </div>
                      <span title="手机号码" style="display: inline-block;color: var(--el-color-primary);width: 90px;">{{ item.phone }}</span>
                      </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="学员:" prop="toStudentID">
                <el-select
                  filterable
                  v-model="mergeFormData.toStudentID"
                  placeholder="请选择学员" 
                  clearable
                >
                <el-option
                    v-for="item in studentList"
                    :key="item.id"
                    :label="item.code+'-'+item.wechatNickname+'-'+item.phone"
                    :value="item.id"
                  >
                      <div>
                      <div style="display: inline-block;width: 200px;">
                        <span title="学员编号">{{ item.code }}</span>
                        <span title="微信昵称" style="float:right;color:#c7c7c7;margin-right: 5px;">{{ item.wechatNickname }}</span>
                      </div>
                      <span title="手机号码" style="display: inline-block;color: var(--el-color-primary);width: 90px;">{{ item.phone }}</span>
                      </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer" style="text-align: right;margin-right: 3%;">
          <el-button  size="small" @click="mergeVisable = false"> 取 消 </el-button>
          <el-button  size="small" type="primary" @click="saveMerge"> 保 存 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { selectByPage, deleteStudent, exportStudent, getAll, mergeStudent } from '@/api/oss/student.js'
import { mapState } from 'vuex'
import AddStudent from './addOrUpdate.vue'
import { selectDictionaryByTypeCode } from '@/api/system/dictionary.js'
import { ElLoading } from 'element-plus'
export default {
    components:{
     AddStudent
    },
    data() {
      const validateStudentID = (rule, value, callback) => {
          if(value) {
            if (this.mergeFormData.fromStudentID == this.mergeFormData.toStudentID) {
              callback(new Error('请选择两位不同的学员'))
            }
          } else {
            callback(new Error('请选择学员'))
          }
      }
        return {
            tableTotal: 0,
            tableLoading: false,
            tableData: [],
            // 查询参数
            queryParams: {
                pageNo: 1,
                pageSize: 500,
                name: '',
                wechatID:'',
                weMediaPlatform:'',
                account:'',
                recommendedDateStart:'',
                recommendedDateEnd:'',
            },
            columnList:[
                {prop:'phone',label:'手机号',sortable:false,sort:0,hide:false,fixed:true,width:150},
                {prop:'name',label:'学员姓名',sortable:false,sort:0,hide:false,fixed:true,width:150},
                {prop:'code',label:'学员代码',sortable:false,sort:0,hide:false,fixed:true,width:120},
                {prop:'wechatID',label:'微信号',sortable:false,sort:0,hide:false,fixed:false,width:150},
                {prop:'wechatNickname',label:'微信昵称',sortable:false,sort:0,hide:false,fixed:false,width:120},
                {prop:'weMediaPlatform',label:'自媒体平台',sortable:false,sort:0,hide:false,fixed:false,width:120},
                {prop:'weMediaAccount',label:'自媒体账号',sortable:false,sort:0,hide:false,fixed:false,width:120},
                {prop:'platformNickname',label:'平台粉丝昵称',sortable:false,sort:0,hide:false,fixed:false,width:150},
                {prop:'account',label:'账号(保证金监控中心)',sortable:false,sort:0,hide:false,fixed:false,width:150},
                // {prop:'password',label:'密码(保证金监控中心)',sortable:false,sort:0,hide:false,fixed:false,width:150},
                // {prop:'loginPassword',label:'密码(登录)',sortable:false,sort:0,hide:false,fixed:false,width:150},
                {prop:'tvAnchor',label:'主播',sortable:false,sort:0,hide:false,fixed:false,width:150},
                {prop:'recommended',label:'引流人',sortable:false,sort:0,hide:false,fixed:false,width:150},
                {prop:'studentManager',label:'学员经理',sortable:false,sort:0,hide:false,fixed:false,width:150},
                {prop:'recommendedDate',label:'引流日期',sortable:false,sort:0,hide:false,fixed:false,width:180},
                {prop:'accountLevel',label:'账号等级',sortable:false,sort:0,hide:false,fixed:false,width:150},
                {prop:'groupType',label:'组别',sortable:false,sort:0,hide:false,fixed:false,width:150},
                {prop:'vipServer',label:'一对一类型',sortable:false,sort:0,hide:false,fixed:false,width:150},
                {prop:'status',label:'状态',sortable:false,sort:0,hide:false,fixed:false,width:150},
                {prop:'creatorName',label:'创建人',sortable:false,sort:0,hide:false,fixed:false,width:150},
                {prop:'createTime',label:'创建时间',sortable:false,sort:0,hide:false,fixed:false,width:180},
                {prop:'action',label:'操作',sortable:false,sort:0,hide:false,fixed:'right',width:230},
            ],
            tableHeight:(window.innerHeight - 380) + 'px',
            // 自媒体平台字典列表
            weMediaPlatformList:[],
            // 合并弹窗
            mergeVisable:false,
            // 合并的学员表单数据
            mergeFormData : {
              fromStudentID:undefined,
              toStudentID:undefined,
            },
            mergeFormRules: {
              fromStudentID: [
                { required: true, validator: validateStudentID, trigger: ['blur', 'change'] },
              ],
              toStudentID: [
                { required: true, validator: validateStudentID, trigger: ['blur', 'change'] },
              ],
            },
            // 全部学员信息
            studentList:[],
        }
    },
    created() {
        // 列的sort字段按照index赋值
        this.columnList = this.columnList.map((item,index)=>{
          item.sort = index+1
          return item
        })
        this.selectByPage()
    },
    computed:{
        ...mapState(['amplify'])
    },
    mounted(){
        this.$nextTick(()=>{
            this.countTableHeight()
            selectDictionaryByTypeCode({"dicTypeCode":"WeMediaPlatform"}).then(res=>{
                if (res.code == 1) {
                    this.weMediaPlatformList = res.data
                }
            })
        })
    },
    methods: {
      saveMerge(){
        console.log("表单参数=",this.mergeFormData);
        mergeStudent(this.mergeFormData).then(res=>{
          if (res.code == 1) {
            this.mergeVisable = false
            this.$message.success("操作成功")
            this.selectByPage()
          }
        })
      },
      // 打开合并窗口
      openMergeModel(id){
        this.mergeVisable = true
        // 默认选中点击的学员
        this.mergeFormData.fromStudentID = id
        this.mergeFormData.toStudentID = undefined
        getAll().then(res=>{
          if (res.code ==1) {
            this.studentList = res.data
          }
        })
      },
      // 导出数据
      exportDate(){
        // 下载等待提示框
				const loading = ElLoading.service({
					lock: true,
					text: '下载中, 请稍后......',
					background: 'rgba(0, 0, 0, 0.7)',
				})
        exportStudent(this.queryParams).then(res=>{
          this.commonDownload(res)
        }).finally(()=>{
					loading.close()
				})
      },
      // 开始时间的不可选部分(大于结束时间不可选)
      disabledDateStart(date){
        if (this.isNotBlank(this.queryParams.recommendedDateEnd)) {
          let end = new Date(this.queryParams.recommendedDateEnd)
          return date.getTime() > end.getTime();
        } else {
          return false
        }
      },
      // 结束时间不可选部分(小于结束时间不可选)
      disabledDateEnd(date){
        if (this.isNotBlank(this.queryParams.recommendedDateStart)) {
          let start = new Date(this.queryParams.recommendedDateStart)
          return date.getTime() < start.getTime();
        } else {
          return false
        }
      },
      // 获取指定的数字前面的数字数组
      getBeforeNumber(num){
        let returnArray = []
        for (let i=0;i<num;i++) {
          returnArray.push(i)
        }
      },
      disabledHoursStart(val){
        if (this.isNotBlank(this.queryParams.recommendedDateEnd)) {
          let end = new Date(this.queryParams.recommendedDateEnd)
          let hours = end.getHours()
          console.log("禁用的小时范围: ",hours);
          return this.getBeforeNumber(hours)
        } else {
          return []
        }
      },
      disabledHoursEnd(hours){},
      disabledMinutesStart(minutes){
        if (this.isNotBlank(this.queryParams.recommendedDateEnd)) {
          let end = new Date(this.queryParams.recommendedDateEnd)
          let m = end.getMinutes()
          return this.getBeforeNumber(m)
        } else {
          return []
        }
      },
      disabledMinutesEnd(minutes){},
      disabledSecondsStart(seconds){
        if (this.isNotBlank(this.queryParams.recommendedDateEnd)) {
          let end = new Date(this.queryParams.recommendedDateEnd)
          let s = end.getSeconds()
          return this.getBeforeNumber(s)
        } else {
          return []
        }
      },
      disabledSecondsEnd(seconds){},
      editRow(id){
          console.log("openModal----=",id);
          this.$refs.addOrUpdateRef.openModal(id)
      },
      deleteRow(id){
          this.$confirm("请确认是否删除 ?", "警告  ! ! !", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
              deleteStudent({id:id}).then(res => {
                if (res.code == 1) {
                  this.$message.success(res.message)
                  // 重新获取数据
                  this.onSearch()
                } else {
                  this.$message.error(res.message)
                }
              })
            })
      },
      // 打开新增弹窗事件
      openAddModal() {
          this.$refs.addOrUpdateRef.openModal(null)
      },
      // 搜索事件
      onSearch() {
          this.queryParams.pageNo = 1
          this.selectByPage()
      },
      // 分页查询事件
      selectByPage() {
          this.tableLoading = true
          selectByPage(this.queryParams).then((res) => {
              this.tableLoading = false
              if (res.code === 1) {
                  this.tableData = res.data.records
                  this.tableTotal = res.data.total
              }
          }).catch(() => {
              this.tableLoading = false
          })
      },
      // 表格高度
      countTableHeight(){
        let tableHeight = (window.innerHeight - 380) + 'px'
        // 计算搜索区域
        var searchContainerList =  document.getElementsByClassName("searchContainer")
        if (this.arrIsNotEmpty(searchContainerList) && this.arrIsNotEmpty(searchContainerList[0])) {
                  let searchContainerHeight = searchContainerList[0].offsetHeight
                  // header高度+面包屑高度+tab多标签页高度+tab多标签页底部margin的高度
                  let staticHeight = 60+38+30+15
                  if (this.amplify == true) {
                      // 放大后 , 就没有头部, 面包屑, tab多标签页了 , 预留70px给空白 , 并预留50px给分页
                      tableHeight = window.innerHeight - searchContainerHeight - 50 - 70 + 'px'
                  } else {
                      tableHeight = window.innerHeight - (staticHeight + searchContainerHeight) - 50 - 50 + 'px'
                  }
                  this.tableHeight = tableHeight
              }
      },
    },
    watch: {
		amplify(newValue,oldValue) {
			this.countTableHeight()
		},
	},
}
</script>